﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using SharedIFaces;
using System.Data;
using System.IO;
using System.Xml;
using Data;

namespace BL
{
    // singleton-класс для обращения к серверу приложения
    public class WCF_Client : IClient
    {
        static private WCF_Client _instance = null;
        static public WCF_Client Instance
        {
            get
            {
                if (null == _instance)
                {
                    _instance = new WCF_Client();
                }

                return _instance;
            }
        }

        // подключение к серверу
        private /*BasicHttpBinding*/WSDualHttpBinding _binding = new /*BasicHttpBinding*/WSDualHttpBinding();
        private EndpointAddress _address = new EndpointAddress("http://localhost:44444/demoplayerdotnet");
        DuplexChannelFactory<IServer> _factory = null;
        
        // экземпляр объекта реализующего интерфейс IServer
        // для обращения к серверу
        private IServer _channel;

        private WCF_Client() { }

        public void Connect()
        {
            if (null == _factory)
            {
                _factory = new DuplexChannelFactory<IServer>(Instance, _binding, _address);

                _channel = _factory.CreateChannel();
            }
        }

        public void Bind(User user)
        {
            _channel.Bind(user);
        }

        public DataTable GetTable(String table_name)
        {
            DataSet ds = new DataSet();
            String xml_string = _channel.GetTable(table_name);

            System.IO.StringReader xmlSR = new System.IO.StringReader(xml_string);
            ds.ReadXml(xmlSR, XmlReadMode.Auto);
            
            return ds.Tables[table_name];
        }

        public void UpdateTable(String table_name, DataTable content)
        {
            if (null != content)
            {
                String xml_content = content.DataSet.GetXml();

                _channel.UpdateTable(table_name,xml_content);
            }
        }

        public void InsertToTable(String table_name, DataTable content)
        {
            if (null != content)
            {
                String xml_content = content.DataSet.GetXml();

                _channel.InsertToTable(table_name, xml_content);
            }
        }

        public void DeleteFromTable(String table_name, DataTable content)
        {
            if (null != content)
            {
                String xml_content = content.DataSet.GetXml();

                _channel.DeleteFromTable(table_name, xml_content);
            }
        }

        public User CreateUser(String login, String password)
        {
            // запрашиваем создание User у сервера
            User tmp = _channel.CreateUser(login, password);
            // Добавляем полученный с сервера User в Dictionary
            User.AddToAllUsers(tmp);

            return tmp;
        }

        public Song CreateSong(Guid id)
        {
            Song tmp = Song.GetById(id);
            
            if (null == tmp)
            {
                tmp = _channel.CreateSong(id);

                Song.AddToAllSongs(tmp);
            }

            return tmp;
        }

        public Playlist CreatePlaylist(Guid id)
        {
            Playlist tmp = Playlist.GetById(id);

            if (null == tmp)
            {
                tmp = _channel.CreatePlaylist(id);

                Playlist.AddToAllPlaylists(tmp);
            }

            return tmp;
        }

        public List<Playlist> CreatePlaylists(User user)
        {
            List<Playlist> tmp = _channel.CreatePlaylists(user.Name);

            return tmp;
        }

        public List<PlaylistConnector> CreatePlaylistConnectors(Playlist playlist)
        {
            List<PlaylistConnector> tmp = _channel.CreateConnectors(playlist.ID);
            
            if (null != tmp)
            {
                foreach (var connector in tmp)
                {
                    PlaylistConnector.AddToAllPlaylistConnectors((PlaylistConnector)connector);
                }
            }

            return tmp;
        }

        public void DeletePlaylistConnector(PlaylistConnector connector)
        {
            if (null != connector)
            {
                _channel.DeletePlaylistConnector(connector);
            }
        }

        public void SavePlaylistConnector(PlaylistConnector connector)
        {
            if (null != connector)
            {
                _channel.SavePlaylistConnector(connector);
            }
        }

        public void SaveSong(Song song, User user)
        {
            _channel.SaveSongFromUser(song, user);
        }

        #region Члены IClient

        void IClient.PushSong(Song song)
        {
            Song.AddToAllSongs(song);
        }

        #endregion
    }
}
